package com.test.util;

import javax.sound.sampled.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class AudioUtil {
	byte[] data;
	AudioFormat format;
	int length;
	AudioInputStream inputStream;
	
	public AudioUtil(String name) throws UnsupportedAudioFileException, IOException {
		File file=new File(name);
		inputStream=AudioSystem.getAudioInputStream(file);
		format=inputStream.getFormat();
		length=(int)inputStream.getFrameLength();
		data=new byte[length];
		inputStream.read(data);
		inputStream.close();
	}
	
	public void play() {
		Runnable runnable=new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Clip clip=AudioSystem.getClip();
					clip.open(format, data, 0, length);
					clip.start();
				} catch (LineUnavailableException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		new Thread(runnable).start();
	}
	public void cut(AudioInputStream inputStream) throws IOException {
		AudioInputStream audioInputStream=new AudioInputStream(inputStream, format, 1024);
		OutputStream outputStream=new FileOutputStream("G:\\music\\tt.wav");
		AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE,outputStream);
		audioInputStream.close();
	}
	public static void test() throws UnsupportedAudioFileException, IOException {
//		AudioInputStream audioInputStream=new Au
	}
	
	public static void getAudioLength() {
//		Encoder encoder=new Encoder();
		
//		MultimediaInfo multimediaInfo=encoder.getInfo()
	}
	
	public static void main(String[] args) throws UnsupportedAudioFileException, IOException {
//		AudioUtil audioUtil=new AudioUtil("G:\\music\\music.wav");
////		audioUtil.play();
//		audioUtil.cut(audioUtil.inputStream);
		
		 String wavFile1 = "G:\\music\\music.wav";  
	        String wavFile2 = "G:\\music\\dd.wav";  
	  
	        try {  
	            AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(wavFile1));  
//	            AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));  
	            System.out.println(clip1.getFrameLength());
	            AudioFormat audioFormat=clip1.getFormat();
	            AudioInputStream appendedFiles = new AudioInputStream(clip1,clip1.getFormat(),609689);  
	  
	            AudioSystem.write(appendedFiles,   
	                            AudioFileFormat.Type.WAVE,   
	                            new File("D:\\wavAppended.wav"));  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	}
}
